package com.magic.zhixin.utils;

import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

public class ExpireConcurrentMap {


    private static ExpireConcurrentMap expireConcurrentMap = null;
    private  Timer timer = null;
    private  ConcurrentHashMap concurrentHashMap = null;
    private  ConcurrentHashMap<Object,Long> expireTimeConMap = null;
    private  MyTimerTask myTimerTask = null;
    private  Long Frquency = 60*60*1000l;
    public  static synchronized ExpireConcurrentMap newInstance(){
        if(expireConcurrentMap == null){
            expireConcurrentMap = new ExpireConcurrentMap();
        }
        return expireConcurrentMap;
    }
    private ExpireConcurrentMap(){
        timer = new Timer();
        myTimerTask =new MyTimerTask();
        concurrentHashMap = new ConcurrentHashMap();
        expireTimeConMap = new ConcurrentHashMap<Object,Long>();
        timer.scheduleAtFixedRate(myTimerTask,Frquency,Frquency);
    }

    /**
     *
     * @param key
     * @param value
     * @param expireTime  失效时间，单位为毫秒
     */
    public void put(Object key,Object value,Long expireTime){
        concurrentHashMap.put(key,value);
        expireTimeConMap.put(key,System.currentTimeMillis()+expireTime);

    }

    public Object get(Object key){
        Long expiretime = expireTimeConMap.get(key);
        Long currentDatetimeLong = System.currentTimeMillis();
        if(expiretime == null){
            return null;
        }
        if(expiretime < currentDatetimeLong){
            expireTimeConMap.remove(key);
            concurrentHashMap.remove(key);
            return null;
        }
        return concurrentHashMap.get(key);
    }

     class MyTimerTask extends TimerTask{
        @Override
        public void run() {
            Iterator iterator = expireTimeConMap.keySet().iterator();
            Long currentDatetimeLong = System.currentTimeMillis();
            if(iterator.hasNext()){
                Object key = iterator.next();
                Long expireDatetime = expireTimeConMap.get(key);
                if(expireDatetime < currentDatetimeLong){
                    expireTimeConMap.remove(key);
                    concurrentHashMap.remove(key);
                }
            }
        }
    }

}
